import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { ParameterException, Success } from '@/core/HttpException'
import { addInsert, getFieldValues, getFields } from '@/common/utils/sql'
import validator from '@/middlewares/validator'
import schema from '@/common/api-json-schema/system/role/addRole'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/role`,
})
router.post('/add', verifyToken, validator(schema, 'body'), async (ctx: Models.Ctx) => {
  const { roleName, roleCode, resourceList, userList, status } = ctx.request.body as any
  if (!(resourceList.length && userList.length)) {
    throw new ParameterException({ msg: `参数错误：resourceList和userList必须有值` })
  }
  const fieldObj = {
    roleName,
    roleCode,
    status,
  }
  const result = (
    await command(
      addInsert(`INSERT INTO system_role
 (${getFields(fieldObj)})
  values
   (${getFieldValues(fieldObj)}
   );`),
      true,
    )
  ).results
  if (result.affectedRows === 1) {
    // role 新增成功，继续新增关联关系 insertId
    // 新增资源关联关系
    const roleId = result.insertId
    const insertResourceSql = resourceList
      .map(
        (resourceId: any) =>
          `INSERT INTO system_role_resource (role_id, resource_id) values ('${roleId}', '${resourceId}');`,
      )
      .join('')
    const insertUserSql = userList
      .map((userId: any) => `INSERT INTO system_user_role (role_id, user_id) values ('${roleId}', '${userId}');`)
      .join('')
    ;(await command(`${insertResourceSql}${insertUserSql}`)).results
    throw new Success({ data: result, msg: '新增成功' })
  }
})
export default router
